<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Slider extends CI_Controller {
    function __construct(){		
        parent::__construct();
        $this->load->model('slider_model');
    }

    function index(){

$data['result']  = $this->slider_model->get_many_by(array('delete_flag' => UNDELETE_FLAG, 'draft' => DRAFT_NO));

        $data['tpl']     = 'admin/slider/index';
        $this->load->view('layout/master', $data);
    }

    function add(){
        $this->_update();
    }

    function edit($id = 0){
        $this->_update($id);
    }

    function _update($slider_id = 0){
        $slider_id = intval($slider_id);
        $edit_flag = $slider_id != 0 ? true : false;

        if ($_POST){
            $slider_id = intval($this->input->post('slider_id'));
            $info = array(
                'title'        => trim($this->input->post('title')),
                'type'        => trim($this->input->post('type')),
                'content'         => trim($this->input->post('content')),
                'update_date'  => date('Y-m-d H:i:s', time()),
				'position'     => $this->input->post('position'),
                'draft'        => DRAFT_NO,
				'active_flag' => ACTIVE_FLAG
            );

            $result = $this->slider_model->update($slider_id, $info);

            if ($edit_flag){
                $data['msg'] = 'Lưu slide thành công';
            } else {
                $data['msg'] = 'Thêm mới slide công';
            }
        }

        if ($edit_flag){
            $data['data'] = $this->slider_model->get($slider_id);
        } else {
            //Check draft
            $exist = $this->slider_model->get_by(array('draft' => DRAFT_YES, 'user_id' => $_SESSION['admin']['id']));
            if (count($exist) > 0){
                $data['data'] = $exist;
            } else {
                $draft = array('draft' => DRAFT_YES, 'user_id' => $_SESSION['admin']['id'], 'update_date' => date('Y-m-d H:i:s'), 'create_date' => date('Y-m-d H:i:s'));
                $this->slider_model->insert($draft);
                $data['data'] = $draft;
            }
        }


        $data['tpl'] = 'slider/edit';
        $this->load->view('layout/master', $data);
    }

    function delete(){
        if ($_POST){
            $slider_id = $this->input->post('slider_id');
            if (is_array($slider_id)){
                $id = array($slider_id);
            }
            $result = $this->p->update_many($slider_id, array('delete_flag' => DELETE_FLAG));
            echo $result;
        }
    }
}